<?php
/**
 * Created by PhpStorm.
 * User: 96572
 * Date: 2017/4/28
 * Time: 22:01
 */

namespace app\modules\admin\models;
use Yii;
use yii\db\ActiveRecord;

/**
 * Class Role
 * @package app\modules\admin\models
 *  @public string $name
 *  @property string $description
 */
class Role extends ActiveRecord
{
    const UPDATE_SCENARIO = 'UPDATE_SCENARIO';
    const INSERT_SCENARIO = 'INSERT_SCENARIO';
    public function attributes()
    {
        return ['name', 'description'];
    }

    public function scenarios()
    {
        return [
            static::INSERT_SCENARIO => ['name', 'description'],
            static::UPDATE_SCENARIO => ['name', 'description'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'name'=>'角色名称',
            'description'=>'角色描述'
        ];
    }

    public function rules()
    {
        return [
            [['name','description'],'required','message'=>'不能为空'],
            [['name'],'nameIsExist'],
        ];
    }

    public function nameIsExist()
    {
        $role = Yii::$app->authManager->getRole($this->name);
        if (!is_null($role))
        {
            $this->addError(
                'name',
                Yii::t('blog','RBAC_ROLE_EXISTS')
            );
            return false;
        }
        return true;
    }

    /**
     * 创建角色
     * @param bool $runValidation
     * @param null $attributeNames
     * @return bool
     */
    public function save($runValidation = true, $attributeNames = null)
    {
        if ($this->validate())
        {
            $auth = Yii::$app->authManager;
            $role = $auth->createRole($this->name);
            $role->description = $this->description;
            return $auth->add($role);
        }
        return false;
    }

    public static function GetRoles()
    {
        return Yii::$app->authManager->getRoles();
    }
}